class Compiler {
  constructor(vm) {
    this.vm = vm
    this.el = this.vm.$el
    this.compile(this.el)
  }
  compile(el) {
    const nodes = el.childNodes
    Array.from(nodes).forEach(node => {
      if (this.isTextNode(node)) {
        this.compileText(node)
      } else if (this.isElementNode(node)) {
        this.compileElement(node)
      }

      // 递归遍历子节点
      if (node.childNodes && node.childNodes.length) {
        this.compile(node)
      }
    })
  }
  // 转换文本节点
  // {{ msg }}
  compileText(node) {
    const reg = /\{\{(.+)\}\}/
    const textContent = node.textContent
    if (reg.test(textContent)) {
      const key = RegExp.$1.trim()
      node.textContent = this.vm[key]
      new Watcher(this.vm, key, newValue => {
        node.textContent = newValue
      })
    }
  }
  // 转换元素节点
  htmlUpdater(node, value) {
    const _div = document.createElement('div')
    _div.innerHTML = value
    node.appendChild(_div.firstChild)
  }
  modelUpdater(node, value, key) {
    node.value = value
    new Watcher(this.vm, key, newValue => {
      node.value = newValue
    })
    node.addEventListener('input', e => {
      this.vm[key] = node.value
    })
  }
  textUpdater(node, value, key) {
    node.textContent = value
    new Watcher(this.vm, key, newValue => {
      node.textContent = newValue
    })
  }
  update(node, key, directiveName) {
    const updateFn = this[`${directiveName}Updater`]
    updateFn && updateFn.call(this, node, this.vm[key], key)
  }
  updateEvent(node, methodName, directiveName) {
    const [, eventType] = directiveName.split(':')
    //TODO 方法是否在vue实例上面？
    node.addEventListener(eventType, this.vm[methodName].bind(this.vm))
  }
  compileElement(node) {
    const { attributes } = node
    Array.from(attributes).forEach(attr => {
      const attrName = attr.name
      if (this.isDirective(attrName)) {
        // 截取指令名称
        const directiveName = attrName.substr(2)
        const key = attr.value
        if (directiveName.startsWith('on:')) {
          this.updateEvent(node, key, directiveName)
        } else {
          this.update(node, key, directiveName)
        }
      }
    })
  }
  // 判断是否是指令
  isDirective(attrName) {
    return attrName.startsWith('v-')
  }
  // 判断是否是文本节点
  isTextNode(node) {
    return node.nodeType === 3
  }
  // 判断是否是元素节点
  isElementNode(node) {
    return node.nodeType === 1
  }
}